﻿using System;
using System.IO;
using System.Threading.Tasks;
using housingsafety.server.Helpers;
using housingsafety.server.Models;
using housingsafety.server.Svcs;
using Microsoft.AspNetCore.Http;

namespace housingsafety.server.SvcImpls
{
    /// <summary>
    /// 本地磁盘实现
    /// </summary>
    public class DiskImageStorageProvider : IImageStorageProvider
    {
        /// <inheritdoc />
        public string ProviderName => "Disk";

        /// <inheritdoc />
        public async Task<Stream> GetImageStreamAsync(string fileId, string userNumber, string groupName)
        {
            if (string.IsNullOrEmpty(fileId))
            {
                return new MemoryStream();
            }

            if (string.IsNullOrEmpty(userNumber))
            {
                return new MemoryStream();
            }

            string storeFilePath = GetStoreFilePath(fileId, userNumber, groupName);
            if (!File.Exists(storeFilePath))
            {
                return new MemoryStream();
            }

            return await Task.FromResult(File.Open(storeFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
        }

        /// <inheritdoc />
        public async Task<RespRet<FileIndex>> StoreFormFileAsync(IFormFile formFile, string fileId, string userNumber, string groupName)
        {
            if (string.IsNullOrEmpty(userNumber))
            {
                return new RespRet<FileIndex>(false, "userNumber is null", new FileIndex());
            }

            string filePath = GetStoreFilePath(fileId, userNumber, groupName);
            var fileStream = new FileStream(filePath, FileMode.Create);
            await formFile.CopyToAsync(fileStream);
            fileStream.Flush();
            await fileStream.DisposeAsync();

            return new RespRet<FileIndex>(true, "Ok", new FileIndex(fileId, formFile.FileName, formFile.Length));
        }

        private string EnsurePicturesFolder(string userNumber, string groupName)
        {
            string basePath1 = AppContext.BaseDirectory;
            if (string.IsNullOrEmpty(groupName))
            {
                string baseFolder = Path.Combine(basePath1, "pictures");
                Directory.CreateDirectory(baseFolder);
                return baseFolder;
            }
            else
            {
                string baseFolder = Path.Combine(basePath1, "pictures", groupName);
                Directory.CreateDirectory(baseFolder);
                return baseFolder;
            }
        }

        private string GetStoreFilePath(string fileId, string userNumber, string groupName)
        {
            string baseFolder = EnsurePicturesFolder(userNumber, groupName);
            if (fileId.Length < 3)
            {
                string storeFilePath = Path.Combine(baseFolder, $"{fileId}.png");
                return storeFilePath;
            }
            else
            {
                //前2位作为子目录，后XX位作为文件名保存在子目录下
                string subFolder = Path.Combine(baseFolder, fileId.Substring(0, 2));
                Directory.CreateDirectory(subFolder);
                string storeFilePath = Path.Combine(subFolder, $"{fileId.Substring(2)}.png");
                return storeFilePath;
            }
        }
    }
}